import fs from 'fs';
import path from 'path';

export class AuthInfoFile {
  filePath: string;
  constructor(filePath: string) {
    this.filePath = filePath;
  }

  private _fileContent: string | null = null;
  get fileContent() {
    if (!this._fileContent) {
      this._fileContent = fs.readFileSync(path.resolve(this.filePath), "utf-8");
      if (!this._fileContent) throw new Error(`AuthInfoFile ${this.filePath} is empty!`);
    }
    return this._fileContent;
  }

  /**
   * 获取认证列表
   * 例如:
   * canViewAbout: z.boolean(),
   * canDeleteRelease: z.boolean(),
   * ==>
   * ViewAbout
   * DeleteRelease
   */
  getAuthList() {
    const authList = [];
    const authRegex = /(can[A-Z][a-z]+): z\.boolean\(\)/g;
    let match;
    while ((match = authRegex.exec(this.fileContent)) !== null) {
      authList.push(match[1]);
    }
    return authList;
  }
}